package org.example.demo;

import com.intellij.openapi.project.Project;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SqlExecutor {

    public static class Result {
        public boolean isQuery;
        public List<String> columns = new ArrayList<>();
        public List<Map<String, Object>> rows = new ArrayList<>();
        public int affectedRows = -1;
        public long duration;
        public String message;
        public boolean success = false;
    }

    public static Result execute(Project project, String parsedSql) {
        Result result = new Result();
        DataSourceConfig config = DataSourceConfig.getInstance(project);

        String driver = config.getDriverClass(); // 需在 DataSourceConfig 中添加 get 方法
        String url = config.getJdbcUrl();
        String user = config.username;
        String password = config.password;

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            Class.forName(driver);
            long start = System.currentTimeMillis();
            conn = DriverManager.getConnection(url, user, password);
            stmt = conn.createStatement();

            boolean isQuery = parsedSql.trim().toUpperCase().startsWith("SELECT") ||
                              parsedSql.trim().toUpperCase().startsWith("EXPLAIN");

            result.isQuery = isQuery;

            if (isQuery) {
                rs = stmt.executeQuery(parsedSql);
                ResultSetMetaData metaData = rs.getMetaData();
                int colCount = metaData.getColumnCount();

                for (int i = 1; i <= colCount; i++) {
                    result.columns.add(metaData.getColumnName(i));
                }

                int rowCount = 0;
                while (rs.next() && rowCount < 1000) {
                    Map<String, Object> row = new HashMap<>();
                    for (int i = 1; i <= colCount; i++) {
                        row.put(metaData.getColumnName(i), rs.getObject(i));
                    }
                    result.rows.add(row);
                    rowCount++;
                }
                result.message = "查询成功，返回 " + result.rows.size() + " 行";
            } else {
                result.affectedRows = stmt.executeUpdate(parsedSql);
                result.message = "执行成功，影响 " + result.affectedRows + " 行";
            }

            result.duration = System.currentTimeMillis() - start;
            result.success = true;

        } catch (Exception e) {
            result.message = "执行失败: " + e.getMessage();
            result.success = false;
            e.printStackTrace();
        } finally {
            closeQuietly(rs, stmt, conn);
        }

        return result;
    }

    private static void closeQuietly(AutoCloseable... closeables) {
        for (AutoCloseable c : closeables) {
            if (c != null) {
                try { c.close(); } catch (Exception ignored) {}
            }
        }
    }
}